package com.lgj.mall.gateway.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@Configuration
public class CorsConfig{
    @Bean
    public CorsWebFilter corsWebFilter(){
        //1.配置CORS跨域策略
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 不能同时设置allowedOrigin="*"和allowCredentials=true
        // corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedOriginPattern("*"); // 使用pattern代替
        corsConfiguration.addAllowedHeader("*");    //允许所有请求头
        corsConfiguration.addAllowedMethod("*");    //允许所有HTTP方法
        corsConfiguration.setAllowCredentials(true);
        //2.创建URL路由匹配器,指定全局的CORS配置
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",corsConfiguration);//对所有路径生效

        return new CorsWebFilter(source);
    }
}
